<template>
	<view class="tabs-container" :style="containerStyle">
		<!-- 标签栏 -->
		<view class="tabs-header" :class="{ 'tabs-header--scrollable': scrollable }" :style="headerStyle" ref="headerRef">
			<view v-for="(tab, index) in computedTabs" :key="tab.key || index" class="tabs-item" :class="{
          'tabs-item--active': activeKey === (tab.key || index),
          'tabs-item--disabled': tab.disabled
        }" :style="[
          tabItemStyle,
          activeKey === (tab.key || index) ? activeTabItemStyle : {}
        ]" @click="handleTabClick(tab, index)">
				<view class="tabs-item__content">
					<view name="tab" :tab="tab">
						{{ tab.title }}
					</view>
				</view>
				<!-- 激活状态下的指示器 -->
				<view v-if="showIndicator && activeKey === (tab.key || index)" class="tabs-indicator" :style="indicatorStyle">
				</view>
			</view>

			<!-- 滚动指示器 -->
			<view v-if="scrollable && showBarIndicator" class="tabs-scroll-indicator">
				<view class="tabs-scroll-indicator__track" :style="{ 
            width: `${scrollTrackWidth}px`,
            transform: `translateX(${scrollTrackPosition}px)`
          }"></view>
			</view>
		</view>

		<!-- 内容区域 -->
		<view class="tabs-content" :style="contentStyle">
			<slot />
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, computed, watch, onMounted, nextTick, provide } from 'vue';

	// 定义 Tab 项的类型
	export interface TabItem {
		key ?: string | number;
		title : string;
		disabled ?: boolean;
		[key : string] : any; // 允许额外的自定义属性
	}

	// 组件属性定义
	const props = defineProps<{
		// 当前激活的标签 key
		activeKey ?: string | number;
		// 是否可滚动
		scrollable ?: boolean;
		// 是否显示指示器
		showIndicator ?: boolean;
		// 是否在滚动时显示滚动条指示器
		showBarIndicator ?: boolean;
		// 容器样式
		containerStyle ?: string;
		// 头部样式
		headerStyle ?: string;
		// 标签项样式
		tabItemStyle ?: string;
		// 激活的标签项样式
		activeTabItemStyle ?: string;
		// 指示器样式
		indicatorStyle ?: string;
		// 内容区域样式
		contentStyle ?: string;
	}>();

	// 组件事件定义
	const emit = defineEmits<{
		// 标签切换事件
		(e : 'change', key : string | number, tab : TabItem, index : number) : void;
		// 点击标签事件
		(e : 'click', key : string | number, tab : TabItem, index : number) : void;
	}>();

	// 存储从TabPane收集的标签信息
	const panes = ref<TabItem[]>([]);

	// 提供给TabPane的注册方法
	const registerPane = (pane : TabItem) => {
		debugger
		if (!panes.value.some(item => item.key === pane.key)) {
			panes.value.push(pane);
		}
	};

	// 提供给TabPane的注销方法
	const unregisterPane = (key : string | number) => {
		panes.value = panes.value.filter(item => item.key !== key);
	};

	// 提供当前激活的key和注册方法给子组件
	provide('tabs', {
		activeKey: props.activeKey,
		registerPane,
		unregisterPane
	});

	// 内部激活的 key
	const activeKey = ref<string | number>(
		props.activeKey ?? (panes.value.length > 0 ? (panes.value[0].key ?? 0) : '')
	);

	// 计算属性：获取所有标签
	const computedTabs = computed(() => panes.value);
	console.log(computedTabs)
	console.log(panes.value)
	// 标签头部容器元素
	const headerRef = ref<HTMLElement | null>(null);
	// 滚动轨道宽度和位置
	const scrollTrackWidth = ref(0);
	const scrollTrackPosition = ref(0);

	// 处理标签点击
	const handleTabClick = (tab : TabItem, index : number) => {
		if (tab.disabled) return;

		const key = tab.key ?? index;
		emit('click', key, tab, index);

		if (activeKey.value !== key) {
			activeKey.value = key;
			emit('change', key, tab, index);
			adjustScrollPosition();
		}
	};

	// 调整滚动位置，确保激活的标签可见
	const adjustScrollPosition = () => {
		if (!props.scrollable || !headerRef.value) return;

		nextTick(() => {
			const activeElement = headerRef.value?.querySelector('.tabs-item--active');
			if (activeElement && headerRef.value) {
				const headerRect = headerRef.value.getBoundingClientRect();
				const activeRect = activeElement.getBoundingClientRect();

				// 计算需要滚动的位置，使激活的标签居中
				const scrollLeft = activeRect.left - headerRect.left +
					headerRef.value.scrollLeft -
					(headerRect.width / 2 - activeRect.width / 2);

				// 微信小程序中使用scroll-view的scroll-left属性更可靠
				if (headerRef.value.scrollTo) {
					headerRef.value.scrollTo({
						left: scrollLeft,
						behavior: 'smooth'
					});
				} else {
					// 兼容处理
					headerRef.value.scrollLeft = scrollLeft;
				}

				// 更新滚动指示器
				updateScrollIndicator();
			}
		});
	};

	// 更新滚动指示器
	const updateScrollIndicator = () => {
		if (!props.scrollable || !props.showBarIndicator || !headerRef.value) return;

		const { scrollWidth, clientWidth, scrollLeft } = headerRef.value;
		if (scrollWidth <= clientWidth) {
			scrollTrackWidth.value = 0;
			return;
		}

		// 计算滚动指示器宽度和位置
		const trackWidth = (clientWidth / scrollWidth) * clientWidth;
		scrollTrackWidth.value = Math.max(trackWidth, 40); // 最小宽度
		scrollTrackPosition.value = (scrollLeft / scrollWidth) * clientWidth;
	};

	// 监听激活的 key 变化
	watch(
		() => props.activeKey,
		(newVal) => {
			if (newVal !== undefined) {
				activeKey.value = newVal;
				adjustScrollPosition();
			}
		},
		{ immediate: true }
	);

	// 监听panes变化
	watch(
		() => panes.value,
		() => {
			// 如果当前 activeKey 不存在于panes中，重置为第一个
			const exists = panes.value.some(
				(tab, index) => tab.key === activeKey.value || index === activeKey.value
			);

			if (!exists && panes.value.length > 0) {
				activeKey.value = panes.value[0].key ?? 0;
			}

			nextTick(adjustScrollPosition);
		},
		{ deep: true }
	);

	// 组件挂载后初始化
	onMounted(() => {
		adjustScrollPosition();

		// 监听滚动事件更新滚动指示器
		if (props.scrollable && props.showBarIndicator && headerRef.value) {
			headerRef.value.addEventListener('scroll', updateScrollIndicator);
			updateScrollIndicator();
		}
	});

	// 计算属性：是否显示滚动条指示器
	const showBarIndicator = computed(() => {
		if (!props.scrollable || !props.showBarIndicator || !headerRef.value) return false;
		return headerRef.value.scrollWidth > headerRef.value.clientWidth;
	});
</script>

<style scoped>
	.tabs-container {
		width: 100%;
		display: flex;
		flex-direction: column;
	}

	.tabs-header {
		display: flex;
		flex-shrink: 0;
		position: relative;
		overflow: hidden;
		height: 44px;
		border-bottom: 1px solid #eee;
	}

	.tabs-header--scrollable {
		overflow-x: auto;
		-webkit-overflow-scrolling: touch;
	}

	/* 隐藏滚动条但保留功能 */
	.tabs-header::-webkit-scrollbar {
		display: none;
	}

	.tabs-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 0 16px;
		height: 100%;
		cursor: pointer;
		box-sizing: border-box;
		position: relative;
		white-space: nowrap;
		transition: all 0.3s ease;
	}

	.tabs-item__content {
		font-size: 14px;
		color: #333;
		transition: all 0.3s ease;
	}

	.tabs-item--active .tabs-item__content {
		color: #007aff;
		font-weight: 500;
	}

	.tabs-item--disabled {
		opacity: 0.5;
		cursor: not-allowed;
	}

	.tabs-indicator {
		height: 2px;
		background-color: #007aff;
		width: 20px;
		position: absolute;
		bottom: 0;
		transition: all 0.3s ease;
	}

	.tabs-content {
		flex: 1;
		overflow: hidden;
		position: relative;
	}

	.tabs-scroll-indicator {
		height: 3px;
		width: 100%;
		background-color: #f5f5f5;
		position: absolute;
		bottom: 0;
		left: 0;
		z-index: 1;
		pointer-events: none;
	}

	.tabs-scroll-indicator__track {
		height: 100%;
		background-color: rgba(0, 0, 0, 0.2);
		border-radius: 3px;
		transition: all 0.3s ease;
	}
</style>